
import type { EChartsOption, SeriesOption } from 'echarts';
import { mergeOptions } from './mergeOptions';
import theme from '../config/theme.json'
import {
    getLineDefaultOptions,
    setGradientsSeries,
    getLineBarMixedDefaultOptions,
} from './totalLineOptions'
export type TChartTypeMapKey = 'circle' | 'pie' | 'line' | 'numeric' | 'ring' | 'lineBarMixed';

//弹窗-指标种类-出参
export interface IIndicatorDataItem {
    name?: string;
    value?: number;
    rate?: number;
}
export interface IIndicatorDataItemLine {
    name?: string;
    type?: string;
    data?: Array<number>;
}
export interface IIndicatorData {
    name: string;
    // config?: any;
    xAxis?: Array<string>;
    data: Array<IIndicatorDataItem | IIndicatorDataItemLine> | number;
}
export interface IIndicatorDealData extends IIndicatorData {
    type: TChartTypeMapKey;
    options?: EChartsOption;
}

//弹窗-动态-line饼图配置options
/**
 * 获取图表echarts的完整配置的函数
 * @param config 图表的数据信息
 * @param defaultOptions 图表的默认配置
 * @param cb 回调函数
 * @returns 获取图表的完整配置
 */
function setLineOptions(
    config: any,
    defaultOptions: EChartsOption,
    cb?: (s: SeriesOption) => SeriesOption,
): EChartsOption {
    // 打印函数获取到的数据
    console.log('打印函数获取到的数据', config, defaultOptions, cb);

    const s = setGradientsSeries(
        config.data.map((item: any, index: number) => {
            return {
                name: item.name,
                //单独处理质量指标折线颜色(质量指标折线去除阴影, 效能指标反之)
                areaStyle:
                    item.name === '逾期率' || item.name === '完成率'
                        ? {
                            opacity: 0.3,
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [
                                    {
                                        offset: 0,
                                        color: theme.color[index],
                                    },
                                    {
                                        offset: 1,
                                        color: theme.color[index] + '00',
                                    },
                                ],
                            },
                        }
                        : void 0,
                data: item.data.map((ele: any) => Math.floor(ele * 100)),
                legend: {
                    left: '0.5%',
                },
            };
        }),
    );
    console.log('打印组装的series', s);

    // console.log('合并完的配置', mergeOptions(
    //     {
    //         title: {
    //             text: config.name,
    //             left: -5,
    //         },
    //         legend: {
    //             top: '8%',
    //             //动态判断legend位置
    //             left: config.name === 'Bug模块关闭率' || config.name === 'Bug整体关闭率' ? '0.5%' : '80%',
    //         },
    //         grid: {
    //             top: '35%',
    //         },
    //         xAxis: {
    //             type: 'category',
    //             boundaryGap: true,
    //             data: config.xAxis,
    //         },
    //         series: cb ? cb(s) : s,
    //     },
    //     defaultOptions,
    // ));

    // 调用合并图表配置的函数
    return mergeOptions(
        {
            title: {
                text: config.name,
                left: -5,
            },
            legend: {
                top: '8%',
                //动态判断legend位置
                left: config.name === 'Bug模块关闭率' || config.name === 'Bug整体关闭率' ? '0.5%' : '80%',
            },
            grid: {
                top: '35%',
            },
            xAxis: {
                type: 'category',
                boundaryGap: true,
                data: config.xAxis,
            },
            series: cb ? cb(s) : s,
        },
        defaultOptions,
    );
}
//柱状图+折线图
function setLineBarMixedOptions(config: any, defaultOptions: EChartsOption): EChartsOption {
    const m = Math.max(...config.data.map((item: any) => item.data).flat());
    const max = m < 5 ? 5 : m;
    const s = setGradientsSeries(
        config.data.map((item: any) => {
            const obj: any = {
                name: item.name,
                //单独处理质量指标折线颜色
                areaStyle: void 0,
                type: item.type,
                data: item.type === 'line' ? item.data.map((ele: any) => Math.floor(ele * 100)) : item.data,
                tooltip: {
                    valueFormatter: function (value: any) {
                        return item.type === 'line' ? value + ' %' : value + '个';
                    },
                },
                //柱状图显示标签和单位
                label: {
                    show: true,
                    position: 'top',
                    formatter(data: any) {
                        if (data.seriesType === 'bar') {
                            return data.data + '个';
                        } else {
                            return data.data + '%';
                        }
                    },
                },
            };
            if (item.type === 'line') {
                obj.yAxisIndex = 1;
            }
            return obj;
        }),
    );
    return mergeOptions(
        {
            title: {
                text: config.name,
                left: -5,
            },
            xAxis: {
                type: 'category',
                boundaryGap: true,
                data: config.xAxis,
                axisTick: {
                    show: true,
                },
                axisLine: {
                    show: true,
                },
            },
            yAxis: [
                {
                    type: 'value',
                    min: 0,
                    // max: 250,
                    // interval: 50,
                    max: max,
                    interval: Math.ceil(max / 5),
                    axisLine: {
                        show: false,
                    },
                    axisLabel: {
                        formatter: '{value}',
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            type: 'dashed',
                        },
                    },
                },
                {
                    type: 'value',
                    min: 0,
                    max: 100,
                    interval: 20, //每间隔20
                    axisLine: {
                        show: false,
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            type: 'dashed',
                        },
                    },
                    axisLabel: {
                        formatter: '{value} %',
                    },
                },
            ],
            series: s,
        },
        defaultOptions,
    );
}
//格式化百分比不带百分号
export function getPercentageNumber(data: number, n = 0): number {
    // return (parseFloat(data) * 1000) / 10; //保留一位
    return Math.floor(parseFloat((data).toString()) * 100 * Math.pow(10, n)) / Math.pow(10, n);
}
//弹窗-动态-circle饼图配置series
function setPieSeries(list: Array<IIndicatorDataItem>) {
    return list.map((item, i) => {
        const v = getPercentageNumber(item.rate! || item.value!);
        const obj: any = {
            name: v >= 0 ? v + '%' : 0 + '%', //中间的数值
            value: v >= 0 ? v : 0, //饼图占比值
            seriesName: item.name, //提示框里面的title
            tooltipValueShow: '%',
            itemStyle: {
                color: list.length >= 12 ? theme.colorMore[i] : theme.color[i],
            },
        };
        return {
            data: [obj],
        };
    });
}

function picTransparentFormat(data: any, show: any, transparentColor: any) {
    const list: Array<any> = [];
    data.forEach((item: any) => {
        const value = typeof item === 'object' ? item : { value: item };
        list.push(
            {
                ...item,
                //中间的数字
                label: {
                    show,
                    position: 'center',
                    fontSize: 12,
                    fontWeight: 900,
                },
                // 高亮状态的扇区和标签样式(是否变动中间数据)
                emphasis: {
                    scale: false,
                    label: {
                        show: true,
                        backgroundColor: '#fff',
                    },
                },
            },
            {
                value: 100 - value.value,
                tooltip: {
                    show: true,
                },
                itemStyle: {
                    color: transparentColor || 'transparent',
                },
                emphasis: {
                    disabled: true,
                },
            },
        );
    });
    return list;
}
export function setOnePieTransparentSeries(series: any, options: any) {
    const {
        pieW = 20,
        pieP = 10,
        onePicTransparent = false,
        colors = [],
        transparentColor,
    } = options || {};
    return series.map((item: any, i: number) => {
        const radius = [`${100 - pieW - i * (pieP + pieW)}%`, `${100 - i * (pieP + pieW)}%`];
        let data = item.data;
        if (onePicTransparent) {
            data = picTransparentFormat(item.data, i === series.length - 1, transparentColor);
        }
        return {
            type: 'pie',
            radius: radius,
            //视觉引导线
            labelLine: {
                show: false,
            },
            itemStyle: {
                color: colors.length && colors[i] ? colors[i] : theme.color[i],
            },
            // 高亮状态的扇区和标签样式
            // emphasis: {
            //   scale: false, //是否开启高亮后扇区的放大效果
            //   label: {
            //     show: true,
            //     backgroundColor: '#fff',
            //   },
            // },
            ...item,
            data,
        };
    });
}

//弹窗-静态-ring饼图配置options
export function getRingDefaultOptions(): EChartsOption {
    return {
        tooltip: {
            show: true,
        },
    };
}
//定制饼图tooltip数据展示
export function tooltipFormatter(arr: any) {
    if (!Array.isArray(arr)) {
        arr = [arr];
    }
    // 显示axisValueLabel
    const axisName = arr[0].axisValueLabel ? `${arr[0].axisValueLabel}<br/>` : '';
    const s = arr
        .map((item: any) => {
            let after = '';
            if (typeof item.data == 'object' && item.data) {
                //括号内数据
                after = item.data.tooltipValueShow ? `${item.data.tooltipValueShow}` : '';
            }
            // 显示提示框数据
            return `${item.marker}${item.data.seriesName || item.seriesName}: ${item.value}${after}`;
        })
        .join('<br/>');
    return `${axisName}${s}`;
}
//弹窗-动态-ring饼图配置options
export function setRingOptions(
    config: any,
    defaultOptions: EChartsOption,
    cb?: (s: SeriesOption) => SeriesOption,
): EChartsOption {
    const series = setPieSeries(config.data);
    const ser = setOnePieTransparentSeries(series, {
        onePicTransparent: true,
        pieW: 35,
        transparentColor: '#E6E6E6',
        colors: [],
    });
    const options: EChartsOption = {
        series: cb ? cb(ser) : ser,
        tooltip: {
            formatter: tooltipFormatter,
        },
        title: {
            text:config.name
        }
    };
    return mergeOptions(options, defaultOptions);
}
//处理不同类型的图表
export const chartTypeMap: Map<
    TChartTypeMapKey,
    (item: IIndicatorDealData, cb?: (s: SeriesOption) => SeriesOption) => EChartsOption
> = new Map([
    //   [
    //     'circle',
    //     (item: IIndicatorDealData): EChartsOption => {
    //       return setCircleOptions(item, getCircleDefaultOptions());
    //     },
    //   ],
    //   [
    //     'numeric',
    //     (item: IIndicatorDealData): EChartsOption => {
    //       return {
    //         value: item.data[0].value,
    //       };
    //     },
    //   ],
    //   [
    //     'pie',
    //     (item: IIndicatorDealData): EChartsOption => {
    //       return setPieOptions(item, getCircleDefaultOptions());
    //     },
    //   ],
    [
        'line',
        (item: IIndicatorDealData, cb?: (s: SeriesOption) => SeriesOption): EChartsOption => {
            console.log('获取到折线图的数据', item, cb);


            return setLineOptions(item, getLineDefaultOptions(), cb);
        },
    ],
    [
        'ring',
        (item: IIndicatorDealData, cb?: (s: SeriesOption) => SeriesOption): EChartsOption => {
            return setRingOptions(item, getRingDefaultOptions(), cb);
        },
    ],
    [
        'lineBarMixed',
        (item: IIndicatorDealData): EChartsOption => {
            return setLineBarMixedOptions(item, getLineBarMixedDefaultOptions());
        },
    ],
]);
